//
//  MHLocationManager.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/9/25.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHLocationManager.h"

@interface MHLocationManager()<AMapSearchDelegate,AMapLocationManagerDelegate>


@end

NSString *const MHSearchTypes = @"汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";

@implementation MHLocationManager

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static MHLocationManager *instance = nil;
    dispatch_once(&onceToken,^{
        instance = [[super allocWithZone:NULL] init];
        [AMapServices sharedServices].apiKey = KeyForGaoDe;
//        self->locationManager = [[AMapLocationManager alloc]init];
       
    });
    return instance;
}

-(void) startUpdatingLocationWithBlock:(VoidBlock_id) updateLocationBlock
{
    self.updateLocationBlock = updateLocationBlock;
//    self.locationManager = [[AMapLocationManager alloc]init]; 
    self.locationManager.delegate = self;
    [self.locationManager startUpdatingLocation];
}

-(AMapLocationManager *)locationManager
{
    if (!_locationManager  ) {
        _locationManager = [[AMapLocationManager alloc]init];
    }
    return _locationManager;
}

-(void) geocodeSearchWithAddress:(NSString *) address geoBlock:(VoidBlock_id) geoBlock
{
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    self.geocodeBlock = geoBlock;
    AMapGeocodeSearchRequest *geo = [[AMapGeocodeSearchRequest alloc] init];
    geo.address = address;
    [self.search  AMapGeocodeSearch:geo];
    
}

- (void)onGeocodeSearchDone:(AMapGeocodeSearchRequest *)request response:(AMapGeocodeSearchResponse *)response
{
    if (response.geocodes.count == 0)
    {
        return;
    }
    if(self.geocodeBlock)
    {
        self.geocodeBlock(response);
    }
    
}

- (void)amapLocationManager:(AMapLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if([self.delegate respondsToSelector:@selector(mhmapLocationManager:didChangeAuthorizationStatus:)])
    {
        [self.delegate mhmapLocationManager:manager didChangeAuthorizationStatus:status];
    }
    
}

-(void) searhAroundWithKeyWorld:(NSString *)keyWorld location:(CLLocation *) location reslutBlock:(VoidBlock_id_id) reslutBlock
{
    if (keyWorld.length == 0)
    {
        return;
    }
    self.searchAroundBlock = reslutBlock;
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
    request.keywords = keyWorld;
    request.types = MHSearchTypes;
    request.requireSubPOIs      = YES;
    AMapGeoPoint *point = [AMapGeoPoint new];
    point.longitude = location.coordinate.longitude;
    point.latitude = location.coordinate.latitude;
    request.requireExtension = YES;
    [self.search AMapPOIKeywordsSearch:request];
}

-(void) searhAroundWithLocation:(CLLocation *) location reslutBlock:(VoidBlock_id_id) reslutBlock
{
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    self.searchAroundBlock = reslutBlock;
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
    request.types = MHSearchTypes;
    request.sortrule = 0;
    request.requireExtension = YES;
    [self.search AMapPOIAroundSearch: request];
}

- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if (self.searchAroundBlock) {
        self.searchAroundBlock(request,response);
    }
}


- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location
{
    if (self.updateLocationBlock) {
        self.updateLocationBlock(location);
    }
    [self.locationManager stopUpdatingLocation];
}




- (void)openLocationSetting
{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]])
    {
      [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }
}



+ (BOOL)isLocationServiceOpen {
    if ([ CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied ||[ CLLocationManager authorizationStatus] ==  kCLAuthorizationStatusRestricted) {
        return NO;
    } else
        return YES;
}


+(void) uploadLocationToRemote:(CLLocation *)location{
    YYCache *cache=[YYCache cacheWithName:MHCacheGlobleKey];
    NSNumber *number = [cache objectForKey:MHUploadedLocation]; // 优先判断本地缓存
    if (![number boolValue] || ![MHHTTPService sharedInstance].currentUser.isHasPushCircle) {
        [[[MHHTTPService sharedInstance] getUserCirclePushStatus] subscribeNext:^(MHHTTPResponse *respose) {
            BOOL alreadyPush =   ([[(NSDictionary *)respose  objectForKey:@"status"] intValue] == 1);
            if (!alreadyPush) {
                
                    [[[MHHTTPService sharedInstance] userLocationWithLocation:location] subscribeNext:^(id x) {
                        YYCache *cache=[YYCache cacheWithName:MHCacheGlobleKey];
                        [cache setObject:@(true) forKey:MHUploadedLocation];
                    }];

            }else
            {
                [cache setObject:@(true) forKey:MHUploadedLocation];
            }
        }];
    }
}

@end
